using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using FreeLancer.HRB.Services;
using FreeLancer.HRB.Domains;

namespace FreeLancer.HRB.Core.Services
{
  /// <summary>
  /// Services of HRB Core
  /// </summary>
  public class CoreService
  {
    /// <summary>
    /// Loads settings from databse.
    /// </summary>
    /// <returns>Key value pairs of settings.</returns>
    public static StringDictionary LoadSettings()
    {
      StringDictionary dic = new StringDictionary();
      SettingService service = new SettingService();
      TList<Setting> settings = service.GetAll();

      foreach (Setting setting in settings)
      {
        dic.Add(setting.SettingName, setting.SettingValue);
      }

      return dic;
    }

    /// <summary>
    /// Save settings to database.
    /// </summary>
    /// <param name="settings">Setting data.</param>
    public static void SaveSettings(StringDictionary settings)
    {
      if (settings == null)
        throw new ArgumentNullException("settings");

      SettingService service = new SettingService();
      TList<Setting> dbSsettings = new TList<Setting>();

      using (ConnectionScope.CreateTransaction())
      {
        foreach (string key in settings.Keys)
        {
          Setting setting = service.GetBySettingName(key);
          setting.SettingValue = settings[key];
          dbSsettings.Add(setting);
        }
        service.Save(dbSsettings);

        bool success = ConnectionScope.Complete();
        if (!success)
          throw new Exception("Can not complete transaction.");
      }
    }
  }
}
